<template>
  <div class="customer-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form 
        :model="searchForm" 
        :inline="true" 
        class="search-form"
        label-width="100px"
      >
        <el-form-item label="客户代码">
          <el-input
            v-model="searchForm.customerCode"
            placeholder="请输入客户代码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="公司名称">
          <el-input
            v-model="searchForm.companyName"
            placeholder="请输入公司名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="业务经理">
          <el-select
            v-model="searchForm.managerId"
            placeholder="请选择业务经理"
            clearable
            style="width: 200px"
          >
            <el-option 
              v-for="manager in managerOptions" 
              :key="manager.value" 
              :label="manager.label" 
              :value="manager.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="启用" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSearch"
            :loading="loading"
          >
            <i class="fas fa-search"></i>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <i class="fas fa-redo"></i>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表区域 -->
    <el-card class="table-card" shadow="never">
      <!-- 操作按钮区 -->
      <div class="table-header">
        <div class="table-title">客户列表</div>
        <div class="table-actions">
          <el-button 
            type="success" 
            @click="handleAdd"
          >
            <i class="fas fa-plus"></i>
            新增客户
          </el-button>
          <el-button 
            type="danger" 
            @click="handleBatchDelete"
            :disabled="selectedRows.length === 0"
          >
            <i class="fas fa-trash"></i>
            批量删除
          </el-button>
          <el-button 
            type="info" 
            @click="handleExport"
          >
            <i class="fas fa-file-excel"></i>
            导出Excel
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column 
          prop="customerCode" 
          label="客户代码" 
          width="120"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="customerName" 
          label="客户名称" 
          width="150"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="companyName" 
          label="公司名称" 
          min-width="200"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="contactPhone" 
          label="联系人电话" 
          width="130"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="companyAddress" 
          label="公司地址" 
          min-width="200"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="managerName" 
          label="业务经理" 
          width="100"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="status" 
          label="状态" 
          width="80"
          align="center"
        >
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 'active' ? 'success' : 'danger'"
              size="small"
            >
              {{ row.status === 'active' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          label="操作" 
          width="180" 
          fixed="right"
          align="center"
        >
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              text
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              text
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              text
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 {{ total }} 条记录，当前第 {{ currentPage }}/{{ Math.ceil(total / pageSize) || 1 }} 页
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="客户代码" prop="customerCode">
          <el-input 
            v-model="form.customerCode" 
            placeholder="请输入客户代码"
            :disabled="isEdit"
          />
        </el-form-item>
        
        <el-form-item label="客户名称" prop="customerName">
          <el-input 
            v-model="form.customerName" 
            placeholder="请输入客户名称"
          />
        </el-form-item>
        
        <el-form-item label="公司名称" prop="companyName">
          <el-input 
            v-model="form.companyName" 
            placeholder="请输入公司名称"
          />
        </el-form-item>
        
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input 
            v-model="form.contactPhone" 
            placeholder="请输入联系人电话"
          />
        </el-form-item>
        
        <el-form-item label="公司地址" prop="companyAddress">
          <el-input 
            v-model="form.companyAddress" 
            type="textarea" 
            :rows="3"
            placeholder="请输入公司地址"
          />
        </el-form-item>
        
        <el-form-item label="业务经理" prop="managerId">
          <el-select 
            v-model="form.managerId" 
            placeholder="请选择业务经理"
            style="width: 100%"
          >
            <el-option 
              v-for="manager in managerOptions" 
              :key="manager.value" 
              :label="manager.label" 
              :value="manager.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCustomerList, 
  getCustomerById, 
  createCustomer, 
  updateCustomer, 
  deleteCustomer, 
  batchDeleteCustomers, 
  exportCustomers, 
  getManagerOptions,
  checkCustomerCodeUnique
} from '@/api/customer'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const selectedRows = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const tableData = ref([])
const managerOptions = ref([])

// 搜索表单
const searchForm = reactive({
  customerCode: '',
  customerName: '',
  companyName: '',
  managerId: '',
  status: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: '',
  customerCode: '',
  customerName: '',
  companyName: '',
  contactPhone: '',
  companyAddress: '',
  managerId: '',
  status: 'active'
})

// 客户代码唯一性验证器
const validateCustomerCode = async (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }
  
  try {
    const excludeId = isEdit.value ? form.id : null
    const response = await checkCustomerCodeUnique(value, excludeId)
    
    if (response.code === 200) {
      if (response.data.exists) {
        callback(new Error('客户代码已存在，请更换'))
      } else {
        callback()
      }
    } else {
      callback(new Error('代码验证失败，请重试'))
    }
  } catch (error) {
    console.error('客户代码唯一性验证失败:', error)
    callback(new Error('代码验证失败，请重试'))
  }
}

// 表单验证规则
const formRules = {
  customerCode: [
    { required: true, message: '请输入客户代码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    { validator: validateCustomerCode, trigger: 'blur' }
  ],
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  companyAddress: [
    { required: true, message: '请输入公司地址', trigger: 'blur' }
  ],
  managerId: [
    { required: true, message: '请选择业务经理', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取经理姓名
const getManagerName = (managerId) => {
  if (!managerId) return '暂无'
  const manager = managerOptions.value.find(item => item.value === managerId)
  return manager ? manager.label : '未知经理'
}

// 加载客户列表
const loadCustomerList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 过滤空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await getCustomerList(params)
    
    if (response.code === 200) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取客户列表失败')
    }
  } catch (error) {
    console.error('获取客户列表失败:', error)
    ElMessage.error('获取客户列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 加载业务经理选项
const loadManagerOptions = async () => {
  try {
    const response = await getManagerOptions()
    if (response.code === 200) {
      managerOptions.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取业务经理选项失败')
    }
  } catch (error) {
    console.error('获取业务经理选项失败:', error)
    // 使用默认选项
    managerOptions.value = [
      { value: '1', label: '张经理' },
      { value: '2', label: '李经理' },
      { value: '3', label: '王经理' }
    ]
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadCustomerList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  loadCustomerList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增客户'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑客户'
  isEdit.value = true
  Object.keys(form).forEach(key => {
    form[key] = row[key] || ''
  })
  dialogVisible.value = true
}

// 查看
const handleView = async (row) => {
  try {
    const response = await getCustomerById(row.id)
    if (response.code === 200) {
      const customer = response.data
      const managerName = getManagerName(customer.managerId)
      ElMessageBox.alert(
        `
        <div style="text-align: left; line-height: 1.8;">
          <p><strong>客户代码：</strong>${customer.customerCode}</p>
          <p><strong>客户名称：</strong>${customer.customerName}</p>
          <p><strong>公司名称：</strong>${customer.companyName}</p>
          <p><strong>联系人电话：</strong>${customer.contactPhone}</p>
          <p><strong>公司地址：</strong>${customer.companyAddress || '暂无'}</p>
          <p><strong>业务经理：</strong>${managerName}</p>
          <p><strong>状态：</strong><span style="color: ${customer.status === 'active' ? '#67c23a' : '#f56c6c'}">${customer.status === 'active' ? '启用' : '停用'}</span></p>
          <p><strong>创建时间：</strong>${formatDateTime(customer.createdAt)}</p>
          <p><strong>更新时间：</strong>${formatDateTime(customer.updatedAt)}</p>
        </div>
        `,
        '客户详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          customStyle: {
            width: '500px'
          }
        }
      )
    } else {
      ElMessage.error(response.message || '获取客户详情失败')
    }
  } catch (error) {
    console.error('获取客户详情失败:', error)
    ElMessage.error('获取客户详情失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户"${row.customerName}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteCustomer(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadCustomerList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除客户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedRows.value.map(row => row.id)
    const response = await batchDeleteCustomers(ids)
    
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      loadCustomerList()
      selectedRows.value = []
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 导出Excel
const handleExport = async () => {
  try {
    const params = {
      ...searchForm
    }
    
    // 过滤空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await exportCustomers(params)
    
    // 创建下载链接
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `客户列表_${new Date().toISOString().slice(0, 10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出Excel失败:', error)
    ElMessage.error('导出功能暂未实现')
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadCustomerList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadCustomerList()
}

// 重置表单
const resetForm = () => {
  Object.keys(form).forEach(key => {
    if (key === 'status') {
      form[key] = 'active'
    } else {
      form[key] = ''
    }
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    const formData = { ...form }
    delete formData.id // 删除id字段，由后端生成
    
    let response
    if (isEdit.value) {
      response = await updateCustomer(form.id, formData)
    } else {
      response = await createCustomer(formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      dialogVisible.value = false
      loadCustomerList()
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    if (error.message) {
      console.error('提交表单失败:', error)
      ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
    }
    // 表单验证失败时不显示错误消息
  } finally {
    submitLoading.value = false
  }
}

// 页面加载时的初始化
onMounted(() => {
  console.log('客户管理页面已加载')
  loadManagerOptions()
  loadCustomerList()
})
</script>

<style scoped>
.customer-container {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.search-card {
  border-radius: 6px;
  flex-shrink: 0;
}

.search-card :deep(.el-card__body) {
  padding: 16px;
}

.search-form {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.table-card {
  border-radius: 6px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  padding: 16px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-shrink: 0;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.table-actions .el-button {
  padding: 8px 16px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

/* 表格容器自适应高度 */
.table-card :deep(.el-table) {
  flex: 1;
}

.table-card :deep(.el-table__body-wrapper) {
  max-height: calc(100vh - 300px);
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-container {
    gap: 8px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    margin-bottom: 12px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .table-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 12px;
  }
  
  .table-card :deep(.el-table__body-wrapper) {
    max-height: calc(100vh - 350px);
  }
}

/* 优化按钮样式 */
.el-button {
  border-radius: 4px;
  font-weight: 500;
}

.el-button i {
  margin-right: 4px;
}

/* 优化表格样式 */
.table-card :deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

.table-card :deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

.table-card :deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

/* 优化分页样式 */
.pagination-container :deep(.el-pagination) {
  --el-pagination-font-size: 14px;
}

.pagination-container :deep(.el-pagination .btn-prev),
.pagination-container :deep(.el-pagination .btn-next) {
  border-radius: 4px;
}

.pagination-container :deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
}
</style> 